from src.constant.province_city import ProvinceCity as ProvinceCity

import requests
import json


class ProvinceCityUtil:
    """
    省、市的工具类
    """

    # 太平洋的接口，根据IP获取地址
    Pconline_Api_Url = 'http://whois.pconline.com.cn/ipJson.jsp?json=true&ip='

    @staticmethod
    def get_province_and_city(ip):
        """
        根据ip，获取省和市
        :param self:
        :param ip:
        :return:
        """
        # 如果是本地ip，则直接返回
        if ip in ProvinceCity.Local_IP:
            obj = dict()
            obj['province'] = ProvinceCity.Local;
            obj['city'] = ProvinceCity.Local
            return obj

        # 调用太平洋的接口
        response = requests.get(ProvinceCityUtil.Pconline_Api_Url + ip)
        content = str(response.content, encoding='GBK')
        json_object = json.loads(content)
        province = json_object['pro']
        city = json_object['city']
        obj = dict()
        obj['province'] = province;
        obj['city'] = city
        return obj;
